//------------------------------------------------------------------------------
//  <copyright file="TableEnvironment.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Manipulation.MotionPlanning
{
    /// <summary>
    /// Environment has a single table plane at a certain height along the z-axis. Implements a method that returns cost and gradient for a given input point w.r.t this table. Primarily for CHOMP.
    /// </summary>
    public class TableEnvironment : CHOMPEnvironmentRepresentation
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TableEnvironment" /> class
        /// Default table height is 0 m
        /// </summary>
        public TableEnvironment()
        {
            this.TableHeight = 0.0; // default is a table at Z = 0
        }

        /// <summary>
        /// Gets or sets the Height of the table plane along the z-axis (table extends to +-inf in x and y and is at z = tableHeight)
        /// </summary>
        public double TableHeight { get; set; }

        /// <summary>
        /// Computes the cost and gradient at the sphere center assuming that there is a table in the environment at Z = tableHeight m
        /// Cost function restricts the robot to stay above the table. This function is passed as a delegate to the CHOMP planner.
        /// </summary>
        /// <param name="sphereCenter"> Center of the sphere </param>
        /// <param name="sphereRadius"> Radius of the sphere </param>
        /// <param name="epsilon"> Threshold for obstacle avoidance. We want the surface of the sphere to be at least this distance away from the nearest obstacle </param>
        /// <param name="cost"> Cost for the sphere (>= 0) </param>
        /// <param name="grad"> Gradient direction away from obstacles (at the sphere center) </param>
        /// <returns> Flag indicating if the sphere is in collision or not </returns>
        public override bool ComputeSphereCostandGradient(double[] sphereCenter, double sphereRadius, double epsilon, out double cost, out double[] grad)
        {
            // Use temporary cost function: cost = (z_center - radius - z_min)^2 if (z_center - radius) < z_min, 0 otherwise. 
            //  z_surface = z value at the surface of the sphere
            //  z_min = minimum allowed value for the z-coordinate for the sphere (0.03 m for now)
            // Gradient for the cost is = 2 * (z_center - radius - z_min) if (z_center - radius) < z_min, 0 otherwise

            // Get a new threshold that is twice that of the input threshold (we use this for cost and gradient computation)
            double gradBuffer = 2 * epsilon;

            // Incurs cost if robot lies within gradbuffer distance of the table surface
            double surfDist = sphereCenter[2] - this.TableHeight - sphereRadius;
            if (surfDist < gradBuffer)
            {
                // Compute cost
                cost = (surfDist - gradBuffer) * (surfDist - gradBuffer);

                // Compute unit vector in the direction of the gradient - we only have gradient in z direction
                grad = new double[3];
                grad[2] = -1.0; // gradient is 2 * (surfDist - epsilon) / abs(2 * (surfDist - epsilon)) which is -1 as surfdist < epsilon

                // If we are less than epsilon distance away from the obstacle, we set flag to true, else false
                if (surfDist <= epsilon)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                // Compute cost
                cost = 0.0;

                // Compute gradient - gradient is zero
                grad = new double[3];

                // No collision
                return false;
            }
        }
    }
}
